#include "speechrecognition.h"
#include "ui_speechrecognition.h"
#include"httppost.h"
speechrecognition::speechrecognition(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::speechrecognition)
{
    ui->setupUi(this);
}

speechrecognition::~speechrecognition()
{
    delete ui;
}
QString speechrecognition::speechIdentify(QString filename)
{
    // 获取token的请求头应该是application/json
    QString tokenUrl = QString(baiduTokenUrl).arg(client_id).arg(client_secret);
    QMap<QString, QString> tokenHeaders;
    tokenHeaders.insert("Content-Type", "application/json");

    QByteArray requestdata;
    QByteArray replydata;
    httppost httputil;

    bool success = httputil.postMsg(tokenUrl, tokenHeaders, requestdata, replydata);

    if(!success) {
        qDebug() << "获取token失败";
        return "";
    }

    QString key = "access_token";
    accessToken = getJsonvalue(replydata, key);
    if(accessToken.isEmpty()) {
        qDebug() << "解析token失败";
        return "";
    }

    // 语音识别请求
    QString baiduSpeech = QString(baiduSpeechurl).arg(QHostInfo::localHostName()).arg(accessToken);

    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly)) {
        qDebug() << "无法打开音频文件";
        return "";
    }

    requestdata = file.readAll();
    file.close();

    QMap<QString, QString> speechHeaders;
    speechHeaders.insert("Content-Type", "audio/pcm;rate=16000");
    speechHeaders.insert("Content-Length", QString::number(requestdata.size()));

    replydata.clear();
    bool result = httputil.postMsg(baiduSpeech, speechHeaders, requestdata, replydata);

    if(!result) {
        QMessageBox::warning(NULL, "识别提示", "识别请求失败");
        return "";
    }

    key = "result";
    QString text = getJsonvalue(replydata, key);
    if(text.isEmpty()) {
        qDebug() << "识别结果为空，原始响应:" << replydata;
    }
    return text;
}

QString speechrecognition::getJsonvalue(QByteArray ba, QString key)
{
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &parseError);

    if(parseError.error == QJsonParseError::NoError)
    {
        if(jsonDocument.isObject())
        {
            //jsonDocument转化成json对象
            QJsonObject jsonObj = jsonDocument.object();

            //判断是否包含key
            if(jsonObj.contains(key))
            {
                QJsonValue jsonVal = jsonObj.value(key);
                if(jsonVal.isString())  //字符串
                {
                    return jsonVal.toString();
                }
                else if(jsonVal.isArray())  //数组
                {
                    QJsonArray arr = jsonVal.toArray();
                    QJsonValue jv = arr.at(0);
                    return jv.toString();
                }
            }
        }
    }
    return "";
}
